package logic

import (
	"context"
	"gorm.io/gorm"
	"three-sxp/common"
	"three-sxp/models/mysql"

	"three-sxp/orderrpc/internal/svc"
	"three-sxp/orderrpc/orderrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenerateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGenerateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateOrderLogic {
	return &GenerateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GenerateOrderLogic) GenerateOrder(in *orderrpc.GenerateOrderRequest) (*orderrpc.GenerateOrderResponse, error) {
	// todo: add your logic here and delete this line
	cart, _ := mysql.GetCartInfo(mysql.Cart{
		Model: gorm.Model{ID: uint(in.CartId)},
	})
	if cart.ID == 0 {
		return &orderrpc.GenerateOrderResponse{
			Code: 400,
			Msg:  "购物车不存在",
		}, nil
	}
	cartGoods, _ := mysql.GetCartGoodsInfo(mysql.CartGoods{
		CartId: int(in.CartId),
	})
	var money float64
	for _, v := range cartGoods {
		money += v.GoodsPrice * float64(v.GoodsStock)
	}
	sn := common.Random()
	_, err := mysql.CreateOrder(mysql.Order{
		UserId:    cart.UserId,
		UserSn:    sn,
		Money:     money,
		PayStatus: "未支付",
	})
	if err != nil {
		return &orderrpc.GenerateOrderResponse{
			Code: 400,
			Msg:  "生成订单失败",
		}, nil
	}
	return &orderrpc.GenerateOrderResponse{
		Code: 200,
		Msg:  "生成订单成功",
	}, nil
}
